<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`批量${TagManagementUtils.getBatchOperationText(operationType)}`"
    width="700px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="batch-operation-content">
      <!-- 操作说明 -->
      <div class="operation-info">
        <el-alert
          :title="`您即将对 ${selectedTags.length} 个标签执行${TagManagementUtils.getBatchOperationText(operationType)}操作`"
          :type="getAlertType(operationType)"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 标签列表 -->
      <div class="tag-list">
        <h4>选中的标签：</h4>
        <div class="tag-items">
          <div v-for="tag in selectedTags" :key="tag.id" class="tag-item">
            <div class="tag-info">
              <el-tag
                :color="tag.color"
                :style="{ color: getTextColor(tag.color) }"
                class="tag-display"
              >
                {{ tag.name }}
              </el-tag>
              <div class="tag-details">
                <span class="use-count">使用 {{ tag.useCount }} 次</span>
                <el-tag
                  :type="TagManagementUtils.getStatusTagType(tag.status)"
                  size="small"
                >
                  {{ TagManagementUtils.getStatusText(tag.status) }}
                </el-tag>
              </div>
            </div>
            <div class="tag-stats">
              <span class="article-count"
                >{{ tag.articleCount || 0 }} 篇文章</span
              >
              <span class="last-used">{{
                tag.lastUsedTime || "从未使用"
              }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作参数 -->
      <div v-if="needsParameters" class="operation-params">
        <el-form :model="form" label-width="100px">
          <el-form-item
            v-if="operationType === 'UPDATE_COLOR'"
            label="目标颜色"
          >
            <div class="color-input-container">
              <el-input
                v-model="form.targetColor"
                placeholder="请选择颜色"
                style="flex: 1"
              />
              <el-color-picker
                v-model="form.targetColor"
                show-alpha
                :predefine="predefineColors"
              />
            </div>
          </el-form-item>

          <el-form-item label="操作原因">
            <el-input
              v-model="form.reason"
              type="textarea"
              placeholder="请输入操作原因（可选）"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 警告信息 -->
      <div v-if="operationType === 'DELETE'" class="warning-info">
        <el-alert title="删除警告" type="error" :closable="false" show-icon>
          <template #default>
            <div>
              <p>删除操作不可恢复，请确认以下事项：</p>
              <ul>
                <li>被文章使用的标签无法删除</li>
                <li>删除后相关数据将永久丢失</li>
                <li>建议先备份重要数据</li>
              </ul>
              <el-checkbox v-model="form.forceDelete" style="margin-top: 8px">
                强制删除（忽略使用检查）
              </el-checkbox>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 确认输入 -->
      <div v-if="operationType === 'DELETE'" class="confirm-input">
        <el-form label-width="100px">
          <el-form-item label="确认删除">
            <el-input
              v-model="confirmText"
              placeholder="请输入 DELETE 确认删除"
              @input="handleConfirmInput"
            />
            <div class="confirm-tips">
              请输入 <code>DELETE</code> 确认删除操作
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          :type="getButtonType(operationType)"
          :disabled="!canConfirm"
          @click="handleConfirm"
        >
          确认{{ TagManagementUtils.getBatchOperationText(operationType) }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { type TagInfo, TagManagementUtils } from "@/api/tag-management";

interface Props {
  visible: boolean;
  operationType: string;
  selectedTags: TagInfo[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  operationType: "ENABLE",
  selectedTags: () => []
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  confirm: [params: any];
}>();

const dialogVisible = ref(false);
const confirmText = ref("");

// 预定义颜色
const predefineColors = [
  "#f56c6c",
  "#e6a23c",
  "#67c23a",
  "#1890ff",
  "#722ed1",
  "#eb2f96",
  "#fa541c",
  "#fadb14",
  "#52c41a",
  "#13c2c2"
];

// 表单数据
const form = reactive({
  targetColor: "#1890ff",
  reason: "",
  forceDelete: false
});

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      resetForm();
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 计算属性
const needsParameters = computed(() => {
  return ["UPDATE_COLOR", "ENABLE", "DISABLE"].includes(props.operationType);
});

const canConfirm = computed(() => {
  if (props.operationType === "DELETE") {
    return confirmText.value === "DELETE";
  }
  return true;
});

// 方法
const getAlertType = (type: string) => {
  const typeMap: Record<string, string> = {
    ENABLE: "success",
    DISABLE: "warning",
    DELETE: "error",
    UPDATE_COLOR: "info",
    RESET_USE_COUNT: "warning",
    MERGE_TAGS: "info"
  };
  return typeMap[type] || "info";
};

const getButtonType = (type: string) => {
  const typeMap: Record<string, string> = {
    ENABLE: "success",
    DISABLE: "warning",
    DELETE: "danger",
    UPDATE_COLOR: "primary",
    RESET_USE_COUNT: "warning",
    MERGE_TAGS: "primary"
  };
  return typeMap[type] || "primary";
};

const getTextColor = (backgroundColor: string): string => {
  if (!backgroundColor) return "#000000";
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

const resetForm = () => {
  form.targetColor = "#1890ff";
  form.reason = "";
  form.forceDelete = false;
  confirmText.value = "";
};

const handleConfirmInput = (value: string) => {
  confirmText.value = value.toUpperCase();
};

const handleConfirm = () => {
  const params = {
    tagIds: props.selectedTags.map(t => t.id),
    operation: props.operationType,
    reason: form.reason || undefined
  };

  // 根据操作类型添加特定参数
  if (props.operationType === "ENABLE") {
    params.targetStatus = 1;
  } else if (props.operationType === "DISABLE") {
    params.targetStatus = 0;
  } else if (props.operationType === "UPDATE_COLOR") {
    params.targetColor = form.targetColor;
  } else if (props.operationType === "DELETE") {
    params.forceDelete = form.forceDelete;
  }

  emit("confirm", params);
  handleCancel();
};

const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.batch-operation-content {
  max-height: 600px;
  overflow-y: auto;
}

.operation-info {
  margin-bottom: 20px;
}

.tag-list {
  margin-bottom: 20px;
}

.tag-list h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.tag-items {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.tag-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.tag-item:last-child {
  border-bottom: none;
}

.tag-info {
  display: flex;
  flex: 1;
  gap: 12px;
  align-items: center;
}

.tag-display {
  font-weight: 500;
  border: none;
}

.tag-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.use-count {
  font-size: 12px;
  color: #909399;
}

.tag-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.article-count {
  font-size: 12px;
  font-weight: 500;
  color: #606266;
}

.last-used {
  font-size: 12px;
  color: #909399;
}

.operation-params {
  margin-bottom: 20px;
}

.color-input-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.warning-info {
  margin-bottom: 20px;
}

.warning-info ul {
  padding: 0;
  margin: 8px 0 0 20px;
}

.warning-info li {
  margin-bottom: 4px;
  color: #f56c6c;
}

.confirm-input {
  margin-bottom: 20px;
}

.confirm-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.confirm-tips code {
  padding: 2px 4px;
  font-weight: 600;
  color: #e6a23c;
  background-color: #f5f7fa;
  border-radius: 2px;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
